package com.example.study_manger.control;

import com.example.study_manger.entity.TrainingDocument;
import com.example.study_manger.service.DocumentService;
import com.example.study_manger.tools.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/training-documents")
public class TrainingDocumentController {

    @Autowired
    private DocumentService trainingDocumentService;

    // 动态条件查询
    @GetMapping
    public R<List<TrainingDocument>> getAllTrainingDocuments(
            @RequestParam(value = "type", required = false) String type,
            @RequestParam(value = "underReview", required = false) Boolean underReview,
            @RequestParam(value = "published", required = false) Boolean published) {
        List<TrainingDocument> documents = trainingDocumentService.getAllDocuments(type,underReview,published);
        if (documents != null) {
            return R.success(documents);
        }
        return R.fail("没有找到文档");

    }

    // 获取单个文档详细信息
    @GetMapping("/{id}")
    public R<TrainingDocument> getTrainingDocument(@PathVariable Long id) {
        TrainingDocument document = trainingDocumentService.getDocuments(id);
        if (document != null) {
            return R.success(document);
        }
        return R.fail("没有找到文档");
    }

    // 创建新的文档
    @PostMapping
    public R<TrainingDocument> createTrainingDocument(@RequestBody TrainingDocument trainingDocument) {
        TrainingDocument createdDocument = trainingDocumentService.addDocument(trainingDocument);
       if (createdDocument != null) {
            return R.success(createdDocument);
       }return R.fail("创建文档失败");
    }

    // 更新文档
    @PutMapping("/{id}")
    public R<TrainingDocument> updateTrainingDocument(@PathVariable Long id,
                                                      @RequestBody TrainingDocument trainingDocument) {
        System.out.println(trainingDocument);
        TrainingDocument updatedDocument = trainingDocumentService.updateDocument(id, trainingDocument);
        if (updatedDocument != null) {
            return R.success(updatedDocument);
        }
        return R.fail("更新文档失败");
    }

    // 删除文档
    @DeleteMapping("/{id}")
    public R<Boolean> deleteTrainingDocument(@PathVariable Long id) {
       String deleted = trainingDocumentService.deleteDocument(id);
        if (deleted.equals("true")) {
            return R.success(true);
        }
        return R.fail(deleted);
    }
}

